<template>
  <el-dialog
    title="编辑分类"
    :visible.sync="dialogVisibleEdit"
    :before-close="closedDialog"
  >
    <el-form :model="form" ref="ruleForm" label-position="top">
      <el-form-item label="分类名称" :label-width="formLabelWidth">
        <el-input v-model="form.cat_name" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closedDialog">取 消</el-button>
      <el-button type="primary" @click="submitDialog">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    dialogVisibleEdit: {
      type: Boolean,
      default: false
    },
    categoryInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      form: {},
      formLabelWidth: '120px'
    }
  },
  watch: {
    dialogVisibleEdit(val) {
      if (val) {
        console.log(this.categoryInfo)
        this.form = this.categoryInfo
      }
    }
  },
  methods: {
    handleCategoryChange(options) {
      // console.log(options)
    },

    // 关闭窗口事件
    closedDialog() {
      this.$emit('editCategoryClosed')
    },
    async submitDialog() {
      // 处理 form 数据
      const { cat_name: catName, cat_id: catId } = this.form

      if (catName.trim() === '') {
        this.$message.warning('请填写分类名称')
        return
      }

      const { data } = await this.$http.put('/categories/' + catId, {
        cat_name: catName
      })
      if (data.meta.status === 200) {
        // 添加成功后，关闭对话框，更新 category页 表格数据
        this.$message.success(data.meta.msg)
        this.$emit('editCategoryClosed')
        this.$emit('editCategorySuccess')
      } else {
        this.$message.warning(data.meta.msg)
      }
    }
  }
}
</script>

<style></style>
